package nn.api.controller;

import nn.api.util.AdminResponseCode;
import nn.api.util.AdminResponseUtil;
import nn.common.util.JacksonUtil;
import nn.common.util.ResponseUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/api")
public class Login {
    /*
     * { username : value, password : value }
     */
    @PostMapping("/login")
    public Object login(@RequestBody String body) {

//        String username = JacksonUtil.parseString(body, "username");
//        String password = JacksonUtil.parseString(body, "password");
        String username = "dtsadmin";
        String password = "123456";
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ResponseUtil.badArgument();
        }

        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(new UsernamePasswordToken(username, password));
        } catch (UnknownAccountException uae) {

            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        } catch (LockedAccountException lae) {

            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_LOCK_ACCOUNT);

        } catch (AuthenticationException ae) {

            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_AUTH);
        }


        return ResponseUtil.ok(currentUser.getSession().getId());
    }
}
